package com.leo.boot.scheduler.executor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;

import static com.leo.boot.scheduler.util.TaskDecorators.reduce;
import static com.leo.boot.scheduler.util.TaskDecorators.stat;
import static com.leo.boot.scheduler.util.TaskDecorators.trace;

@Configuration
public class ExecutorConfig {

    @Bean
    TaskExecutor task() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setAllowCoreThreadTimeOut(false);
        executor.setRejectedExecutionHandler(new CallerRunsPolicy());
        executor.setThreadNamePrefix("task-");
        executor.setTaskDecorator(reduce(trace(), stat()));
        return executor;
    }

    @Bean
    TaskExecutor simple() {
        SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
        executor.setThreadNamePrefix("simple-");
        executor.setTaskDecorator(reduce(trace(), stat()));
        return executor;
    }
}
